<script setup>
import { onMounted, reactive, ref } from "vue";
import useMessageStore from "@/pinia/modules/messageStore";
import { storeToRefs } from "pinia";
import BackTop from "@/components/backTop/backTop.vue";

const messageStore = useMessageStore();

const { pages, announceList } = storeToRefs(messageStore);

/*获取公告列表的分页参数*/
const params = reactive({
  contentType: 200,
  page: 1,
  pageSize: 10,
});

const scrollTop = ref(0);

const top = ref(0);

/*scroll-view组件上拉刷新的状态*/
const triggered = ref(false);

/*获取公告列表的函数*/
const fetchAnnounceList = async () => {
  try {
    await messageStore.fetchAnnounceList(params);
  } catch (error) {
    uni.showToast({ title: error.message, duration: 2000, icon: "error" });
  }
};

/*scroll-view组件下拉触底的回调函数*/
const scrolltolower = () => {
  if (announceList.value.length >= pages.value) return uni.showToast({ title: "没有更多公告", duration: 2000, icon: "error" });
  fetchAnnounceList();
};

/*scroll-view组件上拉刷新的回调函数*/
const refresherrefresh = async () => {
  triggered.value = true;
  params.page = 1;
  announceList.value = [];
  await fetchAnnounceList();
  triggered.value = false;
};

/*全部已读的回调函数*/
const handleReadAll = async () => {
  try {
    await messageStore.messageReadAll(200);
    uni.showToast({ title: "公告通知已读", duration: 2000, icon: "success" });
  } catch (error) {
    uni.showToast({ title: error.message, duration: 2000, icon: "error" });
  }
};

const goToDetail = async (contentType, announce) => {
  if (announce.isRead === 0) {
    await messageStore.messageRead(contentType, announce.id);
  }
};

const scroll = ({ detail }) => {
  scrollTop.value = detail.scrollTop;
};

onMounted(() => {
  fetchAnnounceList();
});

</script>
<template>
  <scroll-view class="scroll-view" refresher-enabled scroll-y show-scrollbar scroll-with-animation :scroll-top="top" @scroll="scroll" @scrolltolower="scrolltolower" @refresherrefresh="refresherrefresh" :refresher-triggered="triggered">
    <view class="scroll-view-wrapper">
      <view class="message-action">
        <text class="iconfont icon-clear"></text>
        <text @tap="handleReadAll">全部已读</text>
      </view>
      <uni-list :border="false">
        <uni-list-item v-for="(item) in announceList" keep-scroll-position to="/subpkg_message/content/index" :ellipsis="1" :title="item.title" :rightText="item.created" :keep-scroll-position="item.id" @click="goToDetail(200,item)">
          <template v-slot:header>
            <text class="dot" v-if="!item.isRead"></text>
          </template>
        </uni-list-item>
      </uni-list>
      <back-top :show="scrollTop>=700" @click="top=Math.random()"></back-top>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
@import './styles.scss';
</style>
